package org.vacoor.xqq.core.bean;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.IOException;

/**
 * 用户状态
 * <p/>
 * User: Vacoor
 */
@JsonDeserialize(using = Status.StatusIgnoreCaseDeserializer.class)
public enum Status {
    ONLINE(10, "online"),   // 在线
    OFFLINE(20, "offline"), //
    AWAY(30, "away"),       // 离开
    HIDDEN(40, "hidden"),   // 隐身 Invisible
    BUSY(50, "busy"),       // 忙碌
    CALLME(60, "callme"),
    SILENT(70, "silent");   // 不要打扰

    private final int code;
    private final String name;

    Status(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public int getCode() {
        return this.code;
    }

    public String getName() {
        return this.name;
    }

    public static boolean isOfflineStatus(Status status) {
        boolean offline = true;
        if( status != null && Status.HIDDEN != status && Status.OFFLINE != status ) {
            offline = false;
        }
        return offline;
    }

    // -------------------------------------------------

    /**
     * 该反序列化器主要是为了解决将小写状态(eg: online) 转换为 Enum
     */
    static final class StatusIgnoreCaseDeserializer extends JsonDeserializer<Status> {

        @Override
        public Status deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String text = jp.getText();

            if (text == null) {
                return Status.OFFLINE;
            }

            JsonToken curr = jp.getCurrentToken();
            if (curr == JsonToken.VALUE_STRING || curr == JsonToken.FIELD_NAME) {
                Status r = parseStatus(text);
                if (r == null) {
                    r = parseStatus(text.toUpperCase());
                }
                if (r == null) {
                    r = parseStatus(text.toLowerCase());
                }
                return r;
            }
            if (curr == JsonToken.VALUE_NUMBER_INT) {
                return Status.values()[jp.getIntValue()];
            }
            return null;
        }

        private Status parseStatus(String name) {
            try {
                return Status.valueOf(name);
            } catch (RuntimeException e) {
                return null;
            }
        }
    }
}
